package io.kiki.sba.registry.remoting.netty;


import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;

import javax.ws.rs.client.WebTarget;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

@Setter
public class Channel implements io.kiki.sba.registry.api.Channel {

    @Getter
    private final io.kiki.stack.netty.channelManager.Channel channel;


    @Setter
    @Getter
    private io.kiki.stack.netty.processor.AsyncContext asyncContext;

    private Map<String, Object> attributes;


    public Channel(@NonNull io.kiki.stack.netty.channelManager.Channel channel) {
        this.channel = channel;
    }

    @Override
    public InetSocketAddress getRemoteAddress() {
        return channel.getRemoteAddress();
    }

    @Override
    public InetSocketAddress getLocalAddress() {
        return channel.getLocalAddress();
    }

    @Override
    public boolean isConnected() {
        return channel.isFine();
    }

    @Override
    public void setChannelAttribute(String key, Object value) {

        if (value == null) {
            channel.removeAttribute(key);
        } else {
            channel.setAttribute(key, value);
        }
    }

    @Override
    public Object getConnAttribute(String key) {
        return channel.getAttribute(key);
    }

    @Override
    public synchronized Object getAttribute(String key) {
        return attributes == null ? null : attributes.get(key);
    }

    @Override
    public synchronized void setAttribute(String key, Object value) {

        if (attributes == null) {
            attributes = new HashMap<>();
        }
        if (value == null) {
            attributes.remove(key);
        } else {
            attributes.put(key, value);
        }
    }

    @Override
    public WebTarget getWebTarget() {
        return null;
    }

    @Override
    public void close() {
        this.channel.close();
    }


}
